﻿// http://www.agstrout.com/?p=6
package rob.ui {
	public class MouseController{
		import flash.ui.Mouse;
		import flash.display.Stage;
		import flash.events.*;
	
		private var _down:Boolean;
		private var _up:Boolean;
		private var _moved:Boolean;
		private var _x:Number;
		private var _y:Number;
		private var _delta:Number;
		private var _scrolled:Number;
		
		static private var _instance:MouseController = undefined;
	
		function MouseController(){
		}
		
		public static function init(stage:Stage){
			stage.addEventListener(MouseEvent.MOUSE_DOWN, instance.mouseDownHandler);
			stage.addEventListener(MouseEvent.MOUSE_UP, instance.mouseUpHandler);
			stage.addEventListener(MouseEvent.MOUSE_MOVE, instance.mouseMoveHandler);
			stage.addEventListener(MouseEvent.MOUSE_WHEEL, instance.mouseWheelHandler);
			_x = stage.mouseX;
			_y = stage.mouseY;
		}
		
		private function mouseDownHandler(event:MouseEvent){
			_up = false;
			_down = true;
		}
		
		private function mouseUpHandler(event:MouseEvent){
			_up = true;
			_down = false;
		}
		
		private function mouseMoveHandler(event:MouseEvent){
			_dx = event.stageX - _x;
			_dy = event.stageY - _y;
			if(isNaN(_dx)) _dx = _dy = 0;
			_x = event.stageX;
			_y = event.stageY;
			_moved = true;
		}
		
		private function mouseWheelHandler(event:MouseEvent){
			_scrolled = true;
			_delta = event.delta;
		}
		
		public function reset(){
			_dx = _dy = 0;
			_delta = 0;
			_moved = false;
			_scrolled = false;
		}
		
		public function tick(){
			
		}
		
		public static function get instance(){
			if(_instance == null){
				_instance=new MouseController();
			}
			return _instance;
		}
	
		public function get up():Boolean{ return _up; }
		public function get down():Boolean{ return _down;}
		public function get dx():Number{ 
			if(_dx==0) return 0;
			return (_dx > 0) ? 1 : -1;
		}
		public function get dy():Number{ return _dy;}
		public function get moved():Boolean{ return _moved;}
		public function get scrolled():Boolean{ return (_scrolled == 0) ? false: true;}
		public function get delta():Number{ return _delta;}
	}
}